package com.ext.aic.components;

import java.io.File;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

public class ProgressRequestBody extends RequestBody {
    private final File file;
    private final MediaType contentType;
    private final ProgressListener listener;

    public interface ProgressListener {
        void onProgress(long bytesWritten, long totalBytes);
    }

    public ProgressRequestBody(File file, MediaType contentType, ProgressListener listener) {
        this.file = file;
        this.contentType = contentType;
        this.listener = listener;
    }

    @Override
    public MediaType contentType() {
        return contentType;
    }

    @Override
    public long contentLength() {
        return file.length();
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        try (Source source = Okio.source(file)) {
            long totalBytes = contentLength();
            long bytesWritten = 0;
            // 每次写入的缓冲区大小（可根据需要调整）
            long bufferSize = 2048L;
            while (bytesWritten < totalBytes) {
                long readBytes = source.read(sink.buffer(), bufferSize);
                if (readBytes == -1) break;
                bytesWritten += readBytes;
                sink.flush();
                // 触发进度回调（需要控制回调频率）
                if (listener != null) {
                    listener.onProgress(bytesWritten, totalBytes);
                }
            }
        }
    }
}
